using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using CoachingOrganizer.iOS.Controllers.Tools.MoneyCalculation;
using CoachingOrganizer.Logic.Models.Tools.MoneyCalculation;
using CoachingOrganizer.iOS.Decorators;

namespace CoachingOrganizer.iOS.DataSources.Tools.MoneyCalculation
{
    public class ReportDataSource : UITableViewSource
    {
        public const string CellIdentifer = "PeriodGroupReportCell";

        private readonly UITableView _view;
        private readonly ResultsMoneyCalculationDetailsViewController _controller;
        private readonly MoneyCalculationModel _model;
        private readonly SimpleTableDataSourceDecorator<UIViewController, PeriodGroupReportModelBase> _tableCellsSource;
        private List<PeriodGroupReportModelBase> _groups = new List<PeriodGroupReportModelBase>();

        public ReportDataSource(UITableView view, ResultsMoneyCalculationDetailsViewController controller, MoneyCalculationModel model)
        {
            _view = view;
            _controller = controller;
            _model = model;
            _tableCellsSource = new SimpleTableDataSourceDecorator<UIViewController, PeriodGroupReportModelBase>(CellIdentifer, _view, _controller, p => GetPeriodGroupReportModel(p.Row), m => GetPeriodGroupReportController(m));
            UpdateGroups();
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            return _tableCellsSource.GetCell(indexPath);
        }

        public override int RowsInSection(UITableView tableview, int section)
        {
            return _groups.Count;
        }

        private PeriodGroupReportModelBase GetPeriodGroupReportModel(int index)
        {
            return _groups[index];
        }

        private UIViewController GetPeriodGroupReportController(PeriodGroupReportModelBase model)
        {
            return model.Sign > 0 ? (UIViewController)new MoneyCalculationIncomeReportItemViewController(model) : new MoneyCalculationSpentReportItemViewController(model);
        }

        private void UpdateGroups()
        {
            _groups = _model.Report.CurrentPeriodReport.EnumerateIncomesGroups().Union<PeriodGroupReportModelBase>(_model.Report.CurrentPeriodReport.EnumerateSpentsGroups()).ToList();
        }
    }
}